using MediatR;
using WorkOrder.Domain;
using B.S.BaseData.Api.Read.Command.OrderCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;

namespace B.S.BaseData.Api.Read.CommandHandler.OrderCommandHandler
{
    /// <summary>
    /// 处方流转订单查询处理器
    /// </summary>
    public class PrescriptionOrderHandler : IRequestHandler<PrescriptionOrderQueryCommand, APIResult<ApiPaging<PrescriptionOrder>>>
    {
        private readonly IBaseRepository<PrescriptionOrder> _prescriptionRepository;

        public PrescriptionOrderHandler(IBaseRepository<PrescriptionOrder> prescriptionRepository)
        {
            _prescriptionRepository = prescriptionRepository;
        }

        public Task<APIResult<ApiPaging<PrescriptionOrder>>> Handle(PrescriptionOrderQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<ApiPaging<PrescriptionOrder>> result = new APIResult<ApiPaging<PrescriptionOrder>>();
            result.Code = ApiEnum.Success;
            result.Msg = "查询成功";

            var list = _prescriptionRepository.GetAll().Where(p => p.IsDelete == false);

            // 如果没有数据，生成测试数据
            if (!list.Any())
            {
                list = GenerateTestData().AsQueryable();
            }
            Console.WriteLine($"原始数据数量: {list.Count()}");

            // 按时间范围筛选
            if (request.BeginTime != null && request.EndTime != null)
            {
                list = list.Where(p => p.CreateTime >= request.BeginTime && p.CreateTime <= request.EndTime.Value.AddDays(1));
                Console.WriteLine($"按时间筛选后数量: {list.Count()}");
            }

            // 按关键词搜索（患者姓名或手机号）
            if (!string.IsNullOrEmpty(request.Keyword))
            {
                list = list.Where(p => p.PatientName.Contains(request.Keyword) || p.PatientPhone.Contains(request.Keyword));
                Console.WriteLine($"按关键词筛选后数量: {list.Count()}");
            }

            // 分页处理
            var totalCount = list.Count();
            var row = list.OrderByDescending(p => p.CreateTime)
                         .Skip((request.PageIndex - 1) * request.PageSize)
                         .Take(request.PageSize)
                         .ToList();

            Console.WriteLine($"分页后数量: {row.Count()}, PageIndex: {request.PageIndex}, PageSize: {request.PageSize}");

            var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
            var page = new ApiPaging<PrescriptionOrder>
            {
                Total = totalCount,
                TotalPage = totalPage,
                PageData = row
            };

            result.Data = page;
            return Task.FromResult(result);
        }

        /// <summary>
        /// 生成测试数据
        /// </summary>
        /// <returns></returns>
        private List<PrescriptionOrder> GenerateTestData()
        {
            var testData = new List<PrescriptionOrder>();
            var orderStatuses = new[] { "待支付", "已完成", "已失效" };
            var prescriptionStatuses = new[] { "审核通过" };
            var purchaseMethods = new[] { "药店购药", "在线配送", "-" };
            var dispenseStatuses = new[] { "已核准发药", "未核准发药", "-" };
            var departments = new[] { "内科", "外科", "儿科", "妇产科", "心内科", "神经科" };
            var doctors = new[] { "张三", "李四", "王五", "赵六", "钱七", "孙八" };
            var diseases = new[] { "高血压", "糖尿病", "感冒", "胃炎", "失眠", "头痛" };

            for (int i = 1; i <= 30; i++)
            {
                var orderStatus = orderStatuses[i % orderStatuses.Length];
                var createTime = DateTime.Now.AddDays(-i);

                var order = new PrescriptionOrder
                {
                    OrderNumber = $"202002{i:D2}",
                    PrescriptionNumber = $"202002{i:D2}",
                    OrderStatus = orderStatus,
                    PrescriptionStatus = prescriptionStatuses[0],
                    PurchaseMethod = purchaseMethods[i % purchaseMethods.Length],
                    DispenseStatus = dispenseStatuses[i % dispenseStatuses.Length],
                    TotalAmount = 150 + i * 25,
                    CouponAmount = i % 4 == 0 ? 10 : 0,
                    ActualPayment = 150 + i * 25 - (i % 4 == 0 ? 10 : 0),
                    CreateTime = createTime,
                    PaymentMethod = orderStatus != "待支付" ? "微信支付" : null,
                    PaymentTime = orderStatus != "待支付" ? createTime.AddMinutes(5) : null,
                    PatientName = $"患者{i}",
                    PatientGender = i % 2 == 0 ? "男" : "女",
                    PatientAge = 25 + i % 55,
                    PatientPhone = $"1881234{i:D4}",
                    Disease = diseases[i % diseases.Length],
                    LiverFunction = "正常",
                    KidneyFunction = "正常",
                    AllergyHistory = i % 5 == 0 ? "青霉素过敏" : "无",
                    PregnancyStatus = i % 3 == 0 ? "无" : "无",
                    SymptomDescription = $"{diseases[i % diseases.Length]}，持续{i % 7 + 1}天，需要药物治疗",
                    SelectedMedications = "苯磺酸氨氯地平片×1盒，琥珀酸美托洛尔缓释片×3盒",
                    PrescriptionInfoNumber = $"202004{i:D2}121300",
                    PrescriptionDate = createTime.AddHours(-1),
                    PrescriptionStatusDescription = "审核通过",
                    DoctorName = doctors[i % doctors.Length],
                    Department = departments[i % departments.Length],
                    PreliminaryDiagnosis = $"{diseases[i % diseases.Length]}",
                    TreatmentAdvice = "按时服药，定期复查",
                    PrescriptionDetails = "{\"medicines\":[{\"name\":\"苯磺酸氨氯地平片\",\"specification\":\"5mg*7片/盒\",\"quantity\":1,\"usage\":\"口服，每天一次\"}]}",
                    UserName = $"user{i}",
                    Remarks = i % 5 == 0 ? "患者要求加急处理" : "",
                    UpdateTime = createTime.AddHours(1),
                    IsDelete = false
                };

                testData.Add(order);
            }

            return testData;
        }
    }
} 